package com.yy.jhl.ui.manager.activity;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.foamtrace.photopicker.ImageCaptureManager;
import com.foamtrace.photopicker.ImageConfig;
import com.foamtrace.photopicker.PhotoPickerActivity;
import com.foamtrace.photopicker.PhotoPreviewActivity;
import com.foamtrace.photopicker.SelectModel;
import com.foamtrace.photopicker.intent.PhotoPickerIntent;
import com.foamtrace.photopicker.intent.PhotoPreviewIntent;
import com.yy.common.base.BaseActivity;
import com.yy.common.commonutils.Base64;
import com.yy.common.commonutils.FileUtil;
import com.yy.common.commonutils.ImageLoaderUtils;
import com.yy.common.commonutils.StringUtil;
import com.yy.common.commonutils.TimeUtil;
import com.yy.common.commonwidget.LoadingDialog;
import com.yy.common.commonwidget.OnNoDoubleClickListener;
import com.yy.jhl.R;
import com.yy.jhl.app.AppConstant;
import com.yy.jhl.bean.FileInfo;
import com.yy.jhl.bean.InvitePackageInfo;
import com.yy.jhl.bean.InviteUploadInfo;
import com.yy.jhl.bean.LocationInfo;
import com.yy.jhl.interfaces.FileUploadCallBack;
import com.yy.jhl.interfaces.PictureCallBack;
import com.yy.jhl.interfaces.UploadCallBack;
import com.yy.jhl.ui.main.activity.ClipImageActivity;
import com.yy.jhl.ui.main.activity.TakePhotoUploadActivity;
import com.yy.jhl.ui.manager.adapter.PictureAdapter;
import com.yy.jhl.ui.manager.contract.InviteUploadContract;
import com.yy.jhl.ui.manager.presenter.InviteUploadPresenter;
import com.yy.jhl.util.DataRequestUtil;
import com.yy.jhl.util.DialogUtil;
import com.yy.jhl.util.LocationUtil;
import com.yy.jhl.video.MoviePlayActivity;
import com.yy.jhl.video.MovieRecordActivity;

import java.io.IOException;
import java.util.ArrayList;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

import static com.yy.jhl.ui.main.activity.TakePhotoUploadActivity.DO_BIG_IMAGE;
import static com.yy.jhl.ui.main.activity.TakePhotoUploadActivity.UPLOAD_IMG;

/**
 * Created by libingn on 2017/12/18.
 */

public class InviteUploadActivity extends BaseActivity<InviteUploadPresenter> implements InviteUploadContract.View {
    @BindView(R.id.add_pic_img)
    ImageView addPicImg;
    @BindView(R.id.note_edit)
    EditText noteEdit;
    @BindView(R.id.address_text)
    TextView addressText;
    @BindView(R.id.time_text)
    TextView timeText;
    @BindView(R.id.ensure_btn)
    Button ensureBtn;
    @BindView(R.id.address_parent)
    LinearLayout addressParent;
    InvitePackageInfo packageInfo;
    String attachPath = "";
    String lng = "";
    String lat= "";
    String address= "";
    @BindView(R.id.noScrollgridview)
    GridView noScrollgridview;
    PictureAdapter pictureAdapter;
    ImageCaptureManager captureManager;
    ArrayList<String> attachPaths = new ArrayList<>();
    public static void startAction(Context mContext, InvitePackageInfo packageInfo) {
        Intent intent = new Intent(mContext, InviteUploadActivity.class);
        intent.putExtra("packageInfo", packageInfo);
        mContext.startActivity(intent);
    }


    @Override
    public int getLayoutId() {
        return R.layout.act_invite_upload;
    }

    @Override
    public void initView() {
        pictureAdapter = new PictureAdapter(mContext,true);
        noScrollgridview.setAdapter(pictureAdapter);
        noScrollgridview.setOnItemClickListener(new AdapterView.OnItemClickListener() {

            public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
                                    long arg3) {
                if (arg2 == attachPaths.size()) {
                    //
                    showPictureView();
                } else {
                    //预览
                    if (attachPaths.get(arg2).endsWith("mp4")){
                        MoviePlayActivity.startAction(mContext,attachPaths.get(arg2));
                    }else {
                        PhotoPreviewIntent intent = new PhotoPreviewIntent(mContext);
                        intent.setCurrentItem(arg2); // 当前选中照片的下标
                        intent.setPhotoPaths(attachPaths); // 已选中的照片地址
                        startActivityForResult(intent, AppConstant.REQUEST_PREVIEW_CODE);
                    }
                }
            }
        });
        timeText.setText(TimeUtil.formatData(TimeUtil.dateFormatYMD2,System.currentTimeMillis()));
        packageInfo = (InvitePackageInfo) getIntent().getSerializableExtra("packageInfo");
        showTitle("上传信息", new OnNoDoubleClickListener() {
            @Override
            protected void onNoDoubleClick(View v) {
                finish();
            }
        });
        mPresenter.getHistoryInfo(packageInfo.getPack_num());
        locationEvent();
    }
    private void uploadFile(final UploadCallBack callBack){
        try {
            final ArrayList<String> imagePaths = attachPaths;
            String imageUrl = imagePaths.get(0);
            if (imageUrl.startsWith("http")){
                imagePaths.remove(0);
                if (imagePaths.size() != 0){
                    attachPath +=(imageUrl+"#*#");
                    callBack.getCallBack(imagePaths.size());
                    uploadFile(callBack);
                }else {
                    attachPath +=(imageUrl);
                    if (callBack != null){
                        callBack.getCallBack(0);
                    }
                }
            }else {
                String type = "5";
                if (imageUrl.endsWith("mp4")){
                    type = "8";
                }else {
                    type = "5";
                }
                DataRequestUtil.getInstance(mContext).uploadImage(mContext,type, imageUrl, new FileUploadCallBack() {
                    @Override
                    public void success(FileInfo fileInfo) {
                        imagePaths.remove(0);
                        if (imagePaths.size() != 0) {
                            attachPath += (fileInfo.getFilePath() + "#*#");
                            callBack.getCallBack(imagePaths.size());
                            uploadFile(callBack);
                        } else {
                            attachPath += (fileInfo.getFilePath());
                            if (callBack != null) {
                                callBack.getCallBack(0);
                            }
                        }
                    }
                    @Override
                    public void fail() {
                        LoadingDialog.cancelDialogForLoading();
                    }
                });
            }
        }catch (Exception e){

        }
    }
    /**
     * 显示照片弹出框
     */
    private void showPictureView(){
        boolean isShowMovie = true;
        if (attachPaths.size() > 0){
            isShowMovie = false;
        }else {
            isShowMovie = true;
        }
        DialogUtil.showInviteDialogView(mContext,isShowMovie, new PictureCallBack() {
            @Override
            public void getCallBack(int type) {
                switch (type) {
                    case 1:
                        //拍照
                        try {
                            if (captureManager == null) {
                                captureManager = new ImageCaptureManager(mContext);
                            }
                            Intent intent1 = captureManager.dispatchTakePictureIntent();
                            startActivityForResult(intent1, ImageCaptureManager.REQUEST_TAKE_PHOTO);
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
//                        //相册选择
//                        ImageConfig config = new ImageConfig();
//                        config.minHeight = 400;
//                        config.minWidth = 400;
//                        config.mimeType = new String[]{"image/jpeg", "image/png"}; // 图片类型 image/gif ...
//                        config.minSize = 1 * 1024 * 512; // 1Mb 图片大小
//                        PhotoPickerIntent intent = new PhotoPickerIntent(mContext);
//                        intent.setSelectModel(SelectModel.MULTI);
//                        intent.setShowCarema(false); // 是否显示拍照， 默认false
//                        intent.setMaxTotal(9); // 最多选择照片数量，默认为9
//                        intent.setSelectedPaths(attachPaths); // 已选中的照片地址， 用于回显选中状态
//                        // intent.setImageConfig(config);
//                        startActivityForResult(intent, AppConstant.REQUEST_CAMERA_CODE);
                        break;
                    case 2:
                        //拍摄小视频
                        MovieRecordActivity.startAction(mContext,1000);
                        break;
                }
            }
        });
    }
    private void locationEvent(){
        LocationUtil.getInstance(mContext).getBaiDuLocation(new LocationUtil.BDLocationCallBack() {
            @Override
            public void getBDLocation(LocationInfo locationInfo) {
                lat = locationInfo.getLatitude();
                lng = locationInfo.getLongitude();
                address = locationInfo.getCity();
                addressText.setText(address);
            }
        });
    }
    @Override
    protected void onDestroy() {
        super.onDestroy();
        LocationUtil.getInstance(mContext).clearLocation();
    }

    @Override
    public void getHistoryInfoSuccess(InviteUploadInfo info) {
        if (info != null){
            if (!StringUtil.isEmpty(info.getRemark())){
                noteEdit.setText(info.getRemark());
            }
            if (!StringUtil.isEmpty(info.getUpdate_time())){
                timeText.setText(info.getUpdate_time());
            }
            if (!StringUtil.isEmpty(info.getAddress())){
                addressText.setText(info.getAddress());
            }
            if (!StringUtil.isEmpty(info.getImage())){
                attachPath = info.getImage();
                if (!StringUtil.isEmpty(attachPath)){
                    String[] arrays = attachPath.split("\\#\\*\\#");
                    //小视频
                    if (arrays.length == 1 && arrays[0].endsWith("mp4")){

                    }else {
                        for (int i =0;i<arrays.length;i++){
                            attachPaths.add(arrays[i]);
                        }
                        pictureAdapter.setSelectPaths(attachPaths);
                    }
                }
//                ImageLoaderUtils.display(mContext,addPicImg,info.getImage());
            }
        }

    }

    @Override
    public void getHistoryInfoFail() {

    }

    @Override
    public void uploadInfoSuccess(String package_completed,String package_total) {
        LoadingDialog.cancelDialogForLoading();
        if (StringUtil.isEmpty(package_completed)) package_completed = "0";
        String completed = "0";
        int completedNum = Integer.parseInt(package_completed);
        int totalNum = Integer.parseInt(package_total);
        if (totalNum <= completedNum){
            completed = "1";
        }else {
          showLongToast("您目前还有"+(totalNum-completedNum)+"个箱子未扫描，请继续进行扫描操作！");
        }
        UploadHistoryActivity.startAction(mContext,completed,true);
        finish();
    }

    @Override
    public void uploadInfoFail() {
        LoadingDialog.cancelDialogForLoading();
    }

    @OnClick({R.id.add_pic_img, R.id.ensure_btn,R.id.address_parent})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.add_pic_img:
//                startActivityForResult(TakePhotoUploadActivity.getTakePhotoStartIntent(mContext,
//                        DO_BIG_IMAGE, 1, 1, 640, 640,false,imagePath), UPLOAD_IMG);
                break;
            case R.id.ensure_btn:
                final String note = noteEdit.getText().toString().trim();
                if (StringUtil.isEmpty(note)){
                    showShortToast("备注信息不能为空");
                    return;
                }
                attachPath = "";
                LoadingDialog.showDialogForLoading((Activity) mContext,"数据提交中",false);
                uploadFile(new UploadCallBack() {
                    @Override
                    public void getCallBack(int position) {
                        if (position == 0){
                            mPresenter.uploadInfo(packageInfo.getPackage_id(),packageInfo.getBatch_id(),note,attachPath,lng,lat,address);
                        }
                    }
                });
                break;
            case R.id.address_parent:
                locationEvent();
                break;
        }
    }
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                // 选择照片
                case AppConstant.REQUEST_CAMERA_CODE:
                    attachPaths = data.getStringArrayListExtra(PhotoPickerActivity.EXTRA_RESULT);
                    pictureAdapter.setSelectPaths(attachPaths);
                    break;
                // 拍照
                case ImageCaptureManager.REQUEST_TAKE_PHOTO:
                    if (captureManager.getCurrentPhotoPath() != null) {
                        captureManager.galleryAddPic();
                        // 照片地址
                        String imagePaht = captureManager.getCurrentPhotoPath();
                        ClipImageActivity.startAction((Activity) mContext,Uri.parse(imagePaht));
                    }
                    break;
                //裁剪
                case 1234:
                    Uri uri  = data.getParcelableExtra("imageUri");
                    String path = FileUtil.getImageAbsolutePath(this,uri);
                    attachPaths.add(path);
                    pictureAdapter.setSelectPaths(attachPaths);
                    break;
                // 预览
                case AppConstant.REQUEST_PREVIEW_CODE:
                    ArrayList<String> arrays = data.getStringArrayListExtra(PhotoPreviewActivity.EXTRA_RESULT);
                    attachPaths = arrays;
                    pictureAdapter.setSelectPaths(attachPaths);
                    break;
                case 1000:
                    String moviePath = data.getStringExtra("moviePath");
                    showLongToast(moviePath);
                    attachPaths.clear();
                    attachPaths.add(moviePath);
                    pictureAdapter.setSelectPaths(attachPaths);
                    pictureAdapter.setShowAdd(false);
                    break;

//                case UPLOAD_IMG:
//                    if(data != null && data.getExtras() != null) {
//                        final Uri avatarUri = data.getExtras().getParcelable("PATH");
//                        if (avatarUri != null){
//                            String imgPath = avatarUri.getPath();
//                            try {
//
//                                DataRequestUtil.getInstance(mContext).uploadImage("6", Base64.encodeFromFile(imgPath), new FileUploadCallBack() {
//                                    @Override
//                                    public void success(FileInfo fileInfo) {
//                                        attachPath = fileInfo.getFilePath();
//                                        addPicImg.setImageURI(avatarUri);
//                                    }
//                                    @Override
//                                    public void fail() {
//                                    }
//                                });
//                            } catch (Exception e) {
//                                e.printStackTrace();
//                            }
//                        }
//                    }
//                    break;
            }
        }
    }
}
